package com.funny.stock.data.controller;

import com.funny.stock.base.util.ResultUtil;
import com.funny.stock.base.vo.Result;
import com.funny.stock.data.collect.StockPoolService;
import com.funny.stock.data.vo.Stock;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author pengl
 * @date 2020/11/9
 */
@RestController
@RequestMapping("/stock/pool")
public class StockPoolController {

    @Autowired
    StockPoolService stockPoolService;

    @Autowired
    TaskExecutor taskExecutor;

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public Result addStock(Stock stock){
        Stock addStock = stockPoolService.addStock(stock);

        refreshStockPoolList();
        return ResultUtil.success(addStock);
    }

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public Result getStockList(){
        return ResultUtil.success(stockPoolService.getStockList());
    }


    @RequestMapping(value = "/{code}",method = RequestMethod.GET)
    public Result findByCode(@PathVariable String code){
        Stock stock = stockPoolService.findByCode(code);

        refreshStockPoolList();
        return ResultUtil.success(stock);
    }

    @RequestMapping(value = "/delete/{code}",method = RequestMethod.GET)
    public Result removeStock(@PathVariable String code){
        Stock stock = new Stock();
        stock.setCode(code);
        stockPoolService.removeStock(stock);

        refreshStockPoolList();
        return ResultUtil.success(null);
    }

    /**
     * 异步刷新股票池缓存
     */
    public void refreshStockPoolList(){
        taskExecutor.execute(()-> {
            stockPoolService.getStockList();
        });
    }
}
